package com.xzy.servlet;

import com.xzy.domain.Book;
import com.xzy.domain.BookPage;
import com.xzy.service.IBookService;
import com.xzy.service.impl.BookServiceImpl;
import com.xzy.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/client/bookservlet")
public class ClientBookServlet extends BaseServlet {
    IBookService service = new BookServiceImpl();
    protected void bookPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收当前页码和每页显示数两个参数
        Integer pageOn;
        Integer pageSize;
        pageSize = (Integer) WebUtils.getValue(req.getParameter("pageSize"), BookPage.PAGE_SIZE);
        pageOn = (Integer) WebUtils.getValue(req.getParameter("pageOn"), 1);
        BookPage<Book> page = service.getPage(pageOn, pageSize);
        page.setUrl("client/bookservlet?type=bookPage");
        req.setAttribute("page",page);



        req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp);
    }
    protected void bookPageByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //接收当前页码和每页显示数两个参数
        Integer pageOn;
        Integer pageSize;
        Integer min = (Integer) WebUtils.getValue(req.getParameter("min"), 0);
        Integer max = (Integer) WebUtils.getValue(req.getParameter("max"), Integer.MAX_VALUE);
        pageSize = (Integer) WebUtils.getValue(req.getParameter("pageSize"), BookPage.PAGE_SIZE);
        pageOn = (Integer) WebUtils.getValue(req.getParameter("pageOn"), 1);

        BookPage<Book> page = service.getPageByPrice(pageOn, pageSize, min, max);

        //将min和max参数同时写入到分页条跳转URL中
        StringBuilder sb = new StringBuilder("client/bookservlet?type=bookPageByPrice&min="+min);
       //判断传入参数是否有max 若有则写入url 若无则不写入(若写入则会写入默认值Integer.MAX_VALUE)
        if(req.getParameter("max")!=null&&!"".equals(req.getParameter("max"))){
           sb.append("&max="+max);
       }
        //分页条利用此URL进行跳转(在Servlet中设置URL可实现分页条复用)
       page.setUrl(sb.toString());
        req.setAttribute("page",page);

        req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp);
    }
}
